package com.example.sso.sso_client.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.spring.SpringMVCUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Sa-Token 配置类 
 */
@Slf4j
// @Configuration
public class SaTokenConfig implements WebMvcConfigurer {
    
    /**
     * 在后端注册全局过滤器（或拦截器、或全局异常处理），拦截需要登录后才能访问的页面资源，将未登录的访问重定向至登录接口
     * @return SaServletFilter
     */
    /** 注册 [Sa-Token全局过滤器] */
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/sso/*", "/favicon.ico")
                .setAuth(obj -> {
                    if(!StpUtil.isLogin()) {
                        String back = SaFoxUtil.joinParam(SaHolder.getRequest().getUrl(), SpringMVCUtil.getRequest().getQueryString());
                        String backUrl = "/sso/login?back=" + SaFoxUtil.encodeUrl(back);

                        log.info("请求【{}】未登录，引导重定向至【{}】",SaHolder.getRequest().getUrl(), backUrl);
                        SaHolder.getResponse().redirect(backUrl);
                        SaRouter.back();
                    }
                });
    }
}